package mf.com.Service.impl.sys;

import jakarta.annotation.Resource;
import mf.com.Service.sys.SysMenuService;
import mf.com.Utils.AuthContextUtil;
import mf.com.entity.system.SysMenu;
import mf.com.entity.system.SysUser;
import mf.com.exception.CustomExceptionHandler;
import mf.com.mapper.sys.SysMenuByRoleMapper;
import mf.com.mapper.sys.SysMenuMapper;
import mf.com.uilts.TreeBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/3/30 21:10
 * Description:  菜单服务实现层
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Resource
    private SysMenuMapper menuMapper;

    @Resource
    private SysMenuByRoleMapper sysMenuByRoleMapper;

    /**
     * 根据用户iD查询查询对应权限下的菜单
     */
    @Override
    public List<SysMenu> findForSubMenuByUserId() {
        // 获取用户iD
        final SysUser sysUser = AuthContextUtil.get();
        // 根据用户iD查询对应菜单
        final List<SysMenu> menuList = menuMapper.findForSubMenuByUserId(sysUser.getId());
        return TreeBuilder.buildTree(menuList);
    }

    @Override
    public Integer delete(Integer id) {
        // 查询菜单是否有子菜单
        final Integer quantity = menuMapper.findForSubMenuNumber(id);
        if (quantity > 0) {
            // 如果有子菜单提示不能直接删除
            throw new CustomExceptionHandler("请先删除子菜单");
        }
        return menuMapper.delete(id);
    }

    @Override
    public Integer addMenu(SysMenu sysMenu) {
        // 查询传入菜单对应的的菜单有无父级 有将对应父级菜单的 isHalf 修改为0
        sysMenuByRoleMapper.setMenuHalfByRoleId(sysMenu.getParentId());
        return menuMapper.addMenu(sysMenu);
    }


    @Override
    public Integer updateMenu(SysMenu sysMenu) {
        return menuMapper.updateMenu(sysMenu);
    }

    /**
     * 获取所有菜单
     *
     * @return 返回树形菜单
     */
    @Override
    public List<SysMenu> findAllMenu() {
        final List<SysMenu> sysMenus = menuMapper.selectAll();
        return TreeBuilder.buildTree(sysMenus);
    }


}
